package org.dg.iag.crawl;

import java.util.Date;

import org.apache.log4j.Logger;
import org.dg.iag.crawl.interf.StoreInterface;
import org.dg.iag.dao.GenericDAO;
import org.dg.iag.dao.PutDAO;
import org.dg.iag.entity.Log;
import org.dg.iag.entity.Logs;
import org.dg.iag.query.XQueryGet;
import org.dg.iag.util.ApplicationConstants;
import org.dg.iag.util.StorageUtil;
import org.restlet.representation.Representation;

public class ExistFeedStore implements StoreInterface {
	
	public static Logger logger = Logger.getLogger(ExistFeedStore.class);
	
	/**
	 * First time we want to check if the log files exists in eXist 
	 */
	private boolean checkLogFileExistance	= true;
	private boolean saveFirstInTempFolder	= true;

	@Override
	public Log store(Long timeInMilis, String feedTag, String url, Date timestamp,
			Representation representation) {

		StoreInterface siTest	= StorageUtil.getFeedStore("test");

		siTest.store(timeInMilis, feedTag, url, timestamp, representation);

		Log log						= new Log(timeInMilis, feedTag, url, timestamp!=null?timestamp.getTime()+"":"", 
				ApplicationConstants.APP_PATH + ApplicationConstants.IATI_STORAGE_PATH + "/" + feedTag + ".xml",0);
		try {
			if(representation != null) {
				System.out.println("...................Start putIatiString..........: ");
				//PutDAO.putIatiString(feedTag, text);
				PutDAO.putIatiRepresentation(feedTag, representation);
				System.out.println("...................End putIatiString............");
				log.setImportStatus(1);
			}
			else log.setDescription("Feed content is null");

		}catch (RuntimeException e) {
			e.printStackTrace();
			log.setDescription(e.getMessage());
		}
		catch (Exception e) {
			e.printStackTrace();
			log.setDescription(e.getMessage());
		}

		/**
		 * Saving log files now
		 */
		String logFileName				= ApplicationConstants.LOGS_XML_PATTERN.replace("XXX", timeInMilis.toString() );
		if ( this.checkLogFileExistance ) {
			boolean ret		= StorageUtil.checkXmlExists(logFileName, "<Logs />");

			this.checkLogFileExistance	= !ret;
		}

		GenericDAO<Log, Logs> gdao	= new GenericDAO<Log, Logs>(logFileName);
		logger.debug("...................Start Saving Log..........");
		gdao.addElement(log, "/Logs");
		logger.debug("...................End 	Saving Log..........");
		return log;
	}


	
	@Override
	public Log store(Long timeInMilis, String feedTag, String url, Date timestamp, String text, Boolean isGzip) {

		
		StoreInterface siTest	= StorageUtil.getFeedStore("test");
		
		siTest.store(timeInMilis, feedTag, url, timestamp, text,isGzip);
		

		Log log						= new Log(timeInMilis, feedTag, url, timestamp!=null?timestamp.getTime()+"":"", 
				ApplicationConstants.APP_PATH +ApplicationConstants.IATI_STORAGE_PATH + "/" + feedTag + ".xml",0);
		log.setZipped(isGzip);
		try {
			if(text != null) {
				//System.out.println("...................Start putIatiString..........: "+text.length());
				//PutDAO.putIatiString(feedTag, text);
				boolean isFeedOk = PutDAO.putIatiString(feedTag, text, this.saveFirstInTempFolder );
				//System.out.println("...................End putIatiString............");
				if(isFeedOk)	
					log.setImportStatus(1);
			}
			else log.setDescription("Feed content is null");

		}catch (RuntimeException e) {
			e.printStackTrace();
			log.setDescription(e.getMessage());
		}
		catch (Exception e) {
			e.printStackTrace();
			log.setDescription(e.getMessage());
		}
		
		/**
		 * Saving log files now
		 */
		String logFileName				= ApplicationConstants.LOGS_XML_PATTERN.replace("XXX", timeInMilis.toString() );
		if ( this.checkLogFileExistance ) {
			boolean ret		= StorageUtil.checkXmlExists(logFileName, "<Logs />");
			
			this.checkLogFileExistance	= !ret;
		}
		
		GenericDAO<Log, Logs> gdao	= new GenericDAO<Log, Logs>(logFileName);
		
		long id					= System.currentTimeMillis();
//		XQueryGet xqg			= new XQueryGet("", "max(/Logs/Log/id)", false);
//		try {
//			String result			= gdao.getElementsAsString(xqg);
//			id						= Double.valueOf(result).longValue();
//		} catch (Exception e) {
//			// TODO: handle exception
//			
//			e.printStackTrace();
//		}
//		finally{
//			if (id == -1 || id == 0)
//				id = timeInMilis;
//		}
//		log.setId(id+1);
		log.setId(id);
		logger.debug("...................Start adding log..........");
		gdao.addElement(log, "/Logs");
		logger.debug("...................End 	adding Log..........");
		return log;
	}
	
	public void finish () {
		PutDAO.remove(ApplicationConstants.IATI_STORAGE_PATH);
		PutDAO.rename(ApplicationConstants.IATI_STORAGE_PATH_TEMP, ApplicationConstants.IATI_STORAGE_PATH.substring(1));
	}



	@Override
	public void setFirstInTempLocation(boolean firstInTempLocation) {
		this.saveFirstInTempFolder	= firstInTempLocation;
		
	}

}
